package com.chat.api.filter;

import com.chat.api.utils.util.ContextUtil;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LoginFilter implements Filter {

    //配置白名单
    private static List<Pattern> patterns = new ArrayList<>();

    static {
        patterns.add(Pattern.compile("/index"));
        patterns.add(Pattern.compile("/register"));
        patterns.add(Pattern.compile("/templates/login.html"));
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        RedisTemplate redisTemplate = ContextUtil.getBean(RedisTemplate.class);
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(httpResponse);
        HttpSession session = httpRequest.getSession();
//        String url = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
        String url = httpRequest.getRequestURI();
//        if (isInclude(url)){
//            filterChain.doFilter(httpRequest,httpResponse);
//            String sessionId = (String) redisTemplate.opsForValue().get(session.getId());
//            Long expireTime = redisTemplate.opsForValue().getOperations().getExpire(sessionId);
//            if (expireTime < 900){//过期时间如果小于15分钟重新设置过期时间
//                redisTemplate.expire(sessionId,30,TimeUnit.MINUTES);
//            }
//            return;
//        }
//
//        if (session.getAttribute(session.getId()) != null){
//            filterChain.doFilter(httpRequest,httpResponse);
//            redisTemplate.expire(session.getId(),30, TimeUnit.MINUTES);
//            return;
//        }else {
//            wrapper.sendRedirect("/templates/login.html");
//        }
        return;
    }

    @Override
    public void destroy() {

    }

    //判断当前请求是否在白名单
    private boolean isInclude(String url) {
        for (Pattern pattern : patterns) {
            Matcher matcher = pattern.matcher(url);
            if (matcher.matches()) {
                return true;
            }
        }
        return false;
    }
}
